package com.zzsy.carosshopprojects.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.base.util.ToastUtils;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.common.CardReplaceAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.membershipcard.FuCardListAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.membershipcard.MemberShipardAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.common.ReadCardMode;
import com.zzsy.carosshopprojects.base.BaseApplation;
import com.zzsy.carosshopprojects.bean.MemberInfoBean;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.StringUtils;

import org.greenrobot.eventbus.EventBus;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProvider;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 感应卡的dialog
 */
public class GoUpPopupDialog extends DialogFragment {
    private Unbinder unbinder;
    @BindView(R.id.img_shua)
    LinearLayout imgShua;
    @BindView(R.id.tvPay)
    TextView tvOhter;
    private ReadCardMode readCardMode;
    private int select = 0;
    public static final int OPENCARD = 1;//开卡检测
    public static final int REPLACEMENTCARD = 2;//补卡
    public static final int CARDREPLACE = 3;//解绑实体卡

    public static GoUpPopupDialog newInstance(int select, boolean isShow, int kind) {
        GoUpPopupDialog goUpPopupDialog = new GoUpPopupDialog();
        Bundle bundle = new Bundle();
        bundle.putInt("select", select);
        bundle.putBoolean("isShow", isShow);
        bundle.putInt("kind", kind);
        goUpPopupDialog.setArguments(bundle);
        return goUpPopupDialog;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.dialog_gouppop, container, false);
        ScreenAdapterTools.getInstance().loadView(rootView);
        unbinder = ButterKnife.bind(this, rootView);
        loadAnim();
        setShow(getArguments().getBoolean("isShow"));
        select = getArguments().getInt("select");
        readCardMode = getViewModelProvider().get(ReadCardMode.class);
        getLifecycle().addObserver(readCardMode);
        checkCards();
        return rootView;

    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity(), R.style.BottomPopupDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //  dialog.setContentView(R.layout.dialog_gouppop);
        dialog.setCanceledOnTouchOutside(true);
        // 设置弹出框布局参数，宽度铺满全屏，底部。
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);

        return dialog;
    }

    /**
     * 加载动画
     */
    private void loadAnim() {
        imgShua.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.shua_card_anim));
    }

    /**
     * 是否显示底部按钮
     *
     * @param isShow
     */
    private void setShow(boolean isShow) {
        if (isShow) {
            tvOhter.setVisibility(View.VISIBLE);
            tvOhter.setOnClickListener(view -> {//其他方式验证
                dismiss();
                CardReplaceAc.start(getActivity());
            });
        } else {
            tvOhter.setVisibility(View.GONE);
        }
    }


    /**
     * 验卡获取UUID
     */
    private void checkCards() {
        readCardMode.getLiveData().observe(this, uuid -> {
            switch (getArguments().getInt("kind")) {
                case OPENCARD:
                    getUUIDMemeberData(getContext(), uuid, DataUtil.getInstance().getCompanyId());
                    break;
                case REPLACEMENTCARD:
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.REPLACEMENTCARD, uuid));
                    dismiss();
                    break;
                case CARDREPLACE:
                    getUUIDMemeberDataReplaceCard(getContext(), uuid, DataUtil.getInstance().getCompanyId());
                    break;
            }

        });
        readCardMode.checkCards(this);

    }


    /**
     * 实体卡挂失
     *
     * @param context
     * @param uuid
     * @param companyId
     */
    public void getUUIDMemeberData(Context context, String uuid, String companyId) {
        RequestUtils.MemberByUuid(context, uuid, companyId, new MyObserver<MemberInfoBean>(context, false) {
            @Override
            public void onSuccess(MemberInfoBean bean) {
                if (select == 0) {
                    String memberId = bean.getMemberId();
                    if (!StringUtils.isEmpty(memberId)) {
                        showTossts("此卡已经是会员！");
                    } else {
                        showTossts("会员信息异常,请联系管理员！");
                    }
                } else if (select == 1) {
                    if (bean != null) {
                        String memberId = bean.getMemberId();
                        String productId = bean.getProductId();
                        String parentId = bean.getParentId();
                        if (StringUtils.isEmpty(memberId)) {
                            showTossts("暂无该会员信息！");
                            return;
                        }
                        if (StringUtils.isEmpty(productId)) {
                            showTossts("该主卡油品类型异常！");
                            return;
                        }
                        if (!StringUtils.isEmpty(parentId)) {
                            boolean subCard = isSubCard(parentId);
                            if (subCard) {
                                showTossts("副卡暂无该功能！");
                                return;
                            } else {
                                FuCardListAc.start(getContext(), uuid, productId);
                                dismiss();
                            }
                        }
                    }

                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (select == 0) {
                    if (code == 500) {//只要不是code返回值不是200 就跳转到开卡界面
                        MemberShipardAc.start(getActivity(), uuid);
                        dismiss();
                    } else {
                        showTossts(errorMsg);
                    }

                } else if (select == 1) {
                    ToastUtils.showToast(getContext(), errorMsg);
                    dismiss();
                }
            }
        });
    }

    /**
     * 解绑实体卡查询会员信息
     *
     * @param context
     * @param uuid
     * @param companyId
     */
    public void getUUIDMemeberDataReplaceCard(Context context, String uuid, String companyId) {
        RequestUtils.MemberByUuid(context, uuid, companyId, new MyObserver<MemberInfoBean>(context, false) {
            @Override
            public void onSuccess(MemberInfoBean bean) {
                String memberId = bean.getMemberId();
                if (StringUtils.isEmpty(memberId)) {
                    ToastUtils.showToast(context, "此卡暂未开通会员！");
                } else {
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.REPLACEMENTCARDS, uuid));
                }
                dismiss();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(context, errorMsg);
                dismiss();
            }
        });
    }

    private void showTossts(String msg) {
        ToastUtils.showToast(BaseApplation.instance(), msg);
        dismiss();
    }

    /**
     * 验证主卡还是副卡
     */
    public boolean isSubCard(String parentId) {
        if (!"0".equals(parentId)) {
            return true;
        } else {
            return false;
        }
    }

    public ViewModelProvider getViewModelProvider() {
        return new ViewModelProvider(this,
                ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication()));
    }

    @Override
    public void onDestroyView() {
        unbinder.unbind();
        super.onDestroyView();
    }



}
